﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using GameView.Comment;
using GameView.Models;
using GameView.Services;
using GameView.Services.Comment;
using GameView.Views;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Media;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;

namespace GameView.ViewModels
{
    public partial class MainViewModel : ObservableObject, IRecipient<NotificationMsg>
    {
        public MainViewModel(IMessenger messenger, UserService userService)
        {
            InitializeNavigationItems();
            _userService = userService;
            _tcpClientService = new HPSocketTcpClientService();
            _tcpClientService.OnStatusChanged += OnStatusChanged;
            _tcpClientService.OnDataReceived += OnDataReceived;
            _ = ConnectWithDelay();
            if (!StaticValues.LoginInfo.PersonInfo.IdCard.IsNullOrEmpty())
                UserName = $"{StaticValues.LoginInfo.PersonInfo.IdCard}/";
            UserName += StaticValues.LoginInfo.PersonInfo.Account;
            var role = "";
            switch (StaticValues.LoginInfo.PersonInfo.RoleId)
            {
                case 0:
                    role = "游客";
                    IconStr = "";
                    break;

                case 1:
                    role = "管理员";
                    IconStr = "ShieldAccount";

                    break;

                case 3:
                    role = "  商人";
                    IconStr = "Storefront";

                    break;

                case 2:
                    role = "  客服";
                    IconStr = "Support";

                    break;
            }
            UserRole = role + ":";
            _messenger = messenger;
            _messenger.RegisterAll(this);
            RefreshBalanceAsync().ConfigureAwait(false);
        }

        private UserService _userService;
        private readonly IMessenger _messenger;
        private readonly HPSocketTcpClientService _tcpClientService;

        [ObservableProperty]
        private ObservableCollection<NavigationItem> _navigationItems = new();

#nullable enable

        [ObservableProperty]
        private NavigationItem? _selectedNavigationItem;

        [ObservableProperty]
        private object _currentView;

        [ObservableProperty]
        private string _userName;

        [ObservableProperty]
        private string _userRole;

        [ObservableProperty]
        private uint _accountBalance = 0;

        [ObservableProperty]
        private bool isRefreshingBalance;

        [ObservableProperty]
        private string _iconStr = "";

        [ObservableProperty]
        private bool _isMessageDrawerOpen = false;

        private async Task ConnectWithDelay(CancellationToken cancellationToken = default)
        {
            await Task.Delay(1000, cancellationToken);
            await Task.Run(() => _tcpClientService.Connect(), cancellationToken);
        }

        private void InitializeNavigationItems()
        {
            if (StaticValues.LoginInfo.PersonInfo.RoleId != 3)
            {
                foreach (var menu in StaticValues.MenuAll)
                {
                    var od = menu.OrderNo - 6;
                    if (od > 0)
                        continue;
                    menu.OrderNo = Math.Abs(od) + 1;
                }
                StaticValues.MenuAll = StaticValues.MenuAll.OrderBy(q => q.OrderNo).ToList();
            }
            foreach (var menu in StaticValues.MenuAll)
            {
                if (menu.State == 1)
                    continue;
                if (StaticValues.LoginInfo.PersonInfo.RoleId == 3 && menu.Name == "商行充值")
                    menu.Name = "商行记录";
                if (StaticValues.LoginInfo.PersonInfo.RoleId != 3 && menu.Name == "充值记录")
                    menu.Name = "玩家充值";
                NavigationItems.Add(new NavigationItem
                {
                    Title = menu.Name,
                    Icon = menu.Image,
                    ViewType = menu.Permission.GetViewByRoutePath()
                });
            }

            // 默认选中第一个
            if (NavigationItems.Count > 0)
            {
                NavigationItems[0].IsSelected = true;
                NavigateToView(NavigationItems[0].ViewType);
            }
        }

        private void OnStatusChanged(string status)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                GlobalMessage.Instance.ShowWarning(status);
            });
        }

        private List<int> needUpdateBalenceList = [1201, 1207];

        private void OnDataReceived(byte[] data)
        {
            string msgStr = "";
            var message = Encoding.UTF8.GetString(data);
            var message11 = Regex.Unescape(message);
            var msg = JSON.Deserialize<NotificationEntity>(message11);
            if (msg == null)
                msgStr = message;
            else
                msgStr = msg.Content;
            if (msg != null)
            {
                _messenger.Send(new NotificationMsg(msg, null));
                if (StaticValues.LoginInfo.PersonInfo.RoleId == 3 && needUpdateBalenceList.Contains(msg.Type))
                {
                    _ = RefreshBalanceAsync();
                }
                if (msg.Type == 1202)
                {
                    PlayEmbeddedAudio();
                }
                else if (msg.Type == 1206)
                {
                    Application.Current.Dispatcher.Invoke(async () =>
                    {
                        await ExtentHelper.GetService<IDialogService>().ShowDialog(new LoginOutView());
                    });
                }
            }
            Application.Current.Dispatcher.Invoke(() =>
                {
                    if (msgStr.Contains("失败！"))
                        GlobalMessage.Instance.ShowError(msgStr);
                    else
                        GlobalMessage.Instance.ShowInformation(msgStr);
                });
        }

        [RelayCommand]
        private async Task AlartPwdAsync()
        {
            var pwd = ExtentHelper.GetService<ReSetPasswordView>();
            await ExtentHelper.GetService<IDialogService>().ShowDialog(pwd);
        }

        [RelayCommand]
        private void DeletePersonal()
        {
            SecureStorage.Delete("a;ll");
        }

        [RelayCommand]
        private void ToggleMessageDrawer()
        {
            IsMessageDrawerOpen = true;
            GlobalMessage.Instance.UnreadCount = 0;
        }

        [RelayCommand]
        private async Task RefreshBalanceAsync()
        {
            IsRefreshingBalance = true;
            try
            {
                int personId = 0;
                if (StaticValues.LoginInfo.PersonInfo.ParentId > 0)
                    personId = StaticValues.LoginInfo.PersonInfo.ParentId;
                else
                    personId = StaticValues.LoginInfo.PersonInfo.Id;
                var res = await _userService.GetABCAsync(personId);
                AccountBalance = (uint)res.Data;
            }
            finally
            {
                IsRefreshingBalance = false;
            }
        }

        [RelayCommand]
        private void Navigate(NavigationItem item)
        {
            if (item == null) return;
            NavigateToView(item.ViewType);
        }

        private void NavigateToView(Type viewType)
        {
            if (viewType == null) return;

            var view = (UserControl)ExtentHelper.GetService(viewType);
            CurrentView = view;
            Debug.WriteLine($"导航到: {viewType.Name}, 视图实例: {view != null}");
        }

        private void PlayEmbeddedAudio()
        {
            try
            {
                Assembly assembly = Assembly.GetExecutingAssembly();
                string resourceName = "GameView.Icons.edge.wav";
                using var stream = assembly.GetManifestResourceStream(resourceName);
                if (stream != null)
                {
                    SoundPlayer player = new(stream);
                    player.Play();
                }
                else
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        GlobalMessage.Instance.ShowError($"找不到嵌入的音频资源");
                    });
                }
            }
            catch (Exception ex)
            {
                Application.Current.Dispatcher.Invoke(() =>
                {
                    GlobalMessage.Instance.ShowError($"播放音频时出错: {ex.Message}");
                });
            }
        }

        public void Receive(NotificationMsg message)
        {
            if (message.Source == nameof(WithdrawalViewModel))
            {
                if (message.Value.Type == 2003)
                    _ = RefreshBalanceAsync();
            }
        }
    }
}